<template>
  <div v-if="keyword === ''">
    <h1>搜索用户</h1>
  </div>
  <div v-else>
    <div v-if="userList.length === 0 && !loading">
      <h1>没有搜索到用户</h1>
    </div>
    <div v-else style="text-align: left">
      <a-list
          class="user-list"
          :loading="loading"
          item-layout="horizontal"
          :data-source="userList"
      >
        <template #loadMore>
          <!-- TODO 加载更多用户群 -->
        </template>
        <template #renderItem="{ item }">
          <a-list-item>
            <template #actions>
              <router-link :to="{path: '/message-center/own', query: {targetId: item.userId}}">
                <CommentOutlined :size="12"/>
              </router-link>
            </template>
            <a-skeleton avatar :title="false" :loading="!!item.loading" active>
              <a-list-item-meta
                  :description="item.introduce"
              >
                <template #title>
                  <a href="https://www.antdv.com/">{{ item.nickname }}</a>
                </template>
                <template #avatar>
                  <a-avatar :src="item.header" />
                </template>
              </a-list-item-meta>
              <div v-if="!item.subscribe">
                <a-button type="primary" size="small">关注</a-button>
              </div>
            </a-skeleton>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>
</template>

<script setup>
import {onBeforeMount, onBeforeUnmount, ref, watch} from "vue";
import router from "@/router/index.js";
import {searchUser} from "@/api/SearchRequest.js";
import Pubsub from "pubsub-js";
import {message} from "ant-design-vue";
import {CommentOutlined} from "@ant-design/icons-vue";

const keyword = ref('');
const userList = ref([]);
const loading = ref(false);

let searchEventKey = Pubsub.subscribe('searchBegin', (msg, data) => {
  if(data !== '') {
    keyword.value = data;
  }
});
const updateKey = 'updatable';

watch(keyword, (val) => {
  if(val !== '') {
    const hide = message.loading({
      content: '加载用户中...',
      updateKey
    });
    loading.value = true;
    searchUser(val, 'create_time-DESC').then(res => {
      loading.value = false;
      if(res.code === 0) {
        userList.value = res.data;
      } else {
        message.warn({
          content: '用户搜索失败'
        },3);
      }
      hide();
      Pubsub.publish('searchDone', res);
    });
  }
});

onBeforeMount(_=> {
  if(typeof router.currentRoute.value.query.keyword !== 'undefined'
    && router.currentRoute.value.query.keyword !== '') {
    keyword.value = router.currentRoute.value.query.keyword;
  }
})

onBeforeUnmount(_=> {
  Pubsub.unsubscribe(searchEventKey);
})
</script>

<style scoped>
.user-list{
  min-height: 350px;
  max-width: 1000px;
  margin: 12px auto;
  //text-align: left;
}
</style>